﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public partial class CarbonExchange_Countries : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        dsCountries.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsCountries_Select);
        dsCountries.Insert += new EventHandler<Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Save);
        dsCountries.Update += new EventHandler<Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Save);
        dsCountries.Delete += new EventHandler<Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Delete);
        dsLocale.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsLocale_Select);
    }

    void dsLocale_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
        var data = cultures.Select(x => new RegionInfo(x.Name)).GroupBy(x => x.EnglishName).Select(x => new { Name = x.First().EnglishName, Value = x.First().Name, Curency = x.First().CurrencySymbol }).OrderBy(x => x.Name);
        e.SetData(data);
    }

    public override Acms.Bll.Role.Roles[] AllowedRoles
    {
        get { return new Acms.Bll.Role.Roles[] { Acms.Bll.Role.Roles.Administrator}; }
    }

    void dsCountries_Delete(object sender, Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs e)
    {
        var factory = new CarbonExchange.Bll.CountryFactory();
        var id = (int)e.Keys["Id"];
        CarbonExchange.Bll.Country tmp = factory.GetById(id);
        factory.Delete(tmp);
    }

    void dsCountries_Save(object sender, Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs e)
    {
        var factory = new CarbonExchange.Bll.CountryFactory();
        CarbonExchange.Bll.Country tmp = null;
        if (e.Operation == Acms.DataControls.EventDrivenDataSourcePerformOperationEventArgs.Operations.Insert)
        {
            tmp = new CarbonExchange.Bll.Country(AcmsContext.SiteId);
        }
        else
        {
            var id = (int)e.Keys["Id"];
            tmp = factory.GetById(id);
        }
        
        tmp.Locale = e.NewValues["Locale"] as string;
        factory.Save(tmp);
    }

    void dsCountries_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        var factory = new CarbonExchange.Bll.CountryFactory();
        var tmp = factory.GetAllBySiteId(AcmsContext.SiteId).ToArray().AsQueryable();
        tmp = tmp.OrderBy(x => x.Name);
        e.SetData(tmp);
    }
}
